package com.ishitong.platform.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * <p>
 * Title: EncodingFilter
 * </p>
 * <p>
 * Description: 编码过滤器
 * </p>
 * <p>
 * Company: Extimes
 * </p>
 * 
 * @author liufeng
 * @version 1.0
 */
public class EncodingFilter implements Filter
{
	protected FilterConfig fc;

	protected String encoding;

	protected boolean use = true;

	/*
	 * 初始化
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException
	{
		fc = filterConfig;
		encoding = fc.getInitParameter("encoding");
		String value = fc.getInitParameter("use");
		if (value == null)
			return;

		if (!"true".equalsIgnoreCase(value) && !"yes".equalsIgnoreCase(value))
		{
			use = false;
		}
	}

	/*
	 * 过滤过程
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
	{
		if (use && encoding != null)
		{
			try
			{
				request.setCharacterEncoding(encoding);
			} catch (UnsupportedEncodingException ex)
			{
				System.out.println(ex.getMessage());
			}
		}
		filterChain.doFilter(request, response);
	}

	/*
	 * 释放
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy()
	{
		fc = null;
		encoding = null;
	}
}
